package org.yuci.concurency.interrupt.case02;

import java.util.concurrent.Semaphore;

public class Worker implements Runnable {
    
    private Semaphore workPermit;
    
    @Override
    public void run() {
        // Start a new job
        
        try {
            while (true) {
                // Carry out a project
                
                // If the worker is stuck in the project, which means that
                // the worker cannot accomplish the project, then the employ has
                // to interrupt and find someone else to carry out the project
                getStuck();
            }
        } catch (Exception e) {
            // E.g., resign
            
            System.out.println("Exception: " + e.getMessage());
        } finally {
            // quit the job
            workPermit.release();
        }
    }
    
    private void getStuck() {
        while (true) {
            System.out.println("I'm stuck.");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                System.out.println("Not able to sleep too.");
            }
        }
    }

    public Semaphore getWorkPermit() {
        return workPermit;
    }

    public void setWorkPermit(Semaphore workPermit) {
        this.workPermit = workPermit;
    }

}
